//创建节点选择器
// const query = wx.createSelectorQuery()
// query.select('.progress-bar').boundingClientRect()
// query.exec(function(res){
//   app.globalData.barWidth = res[0].width - progressBtnWidth
// })

var util = require("../../utils/util.js");
var app = getApp();
const innerAudioContext = wx.createInnerAudioContext();
const progressBtnWidth = 16;

//引入QQ音乐插件
const musicTool = require("../../utils/QQMusicPlugin/qqMusicTools.js")

//定义播放模式
var MusicPlayMode = {
  normal: 0,  //顺序
  loop: 1,    //单曲循环
  random:2    //随机
};

Page({
  data: {
    //currentTime: util.formatTime(0,'m:s'),
    audioSeek: 0,
    audioTime: 0,
    audioDuration: 0,
    playType: 0,
    currentSong:'',
    title:'',
    imgUrl:'',
    src: '',
    playing: false,
    showTime1: '00:00',
    showTime2: '00:00',
  },

  // 拖动进度条事件
  sliderChange: function(e){
    var that = this;
    innerAudioContext.src = this.data.src;
    //获取进度条百分比
    var value = e.detail.value;
    this.setData({ audioTime: value });
    var duration = this.data.audioDuration;
    //根据进度条百分比及歌曲时间，计算拖动位置的时间
    value = parseInt(value * duration / 100);
    //更改状态
    this.setData({ audioSeek: value})
    app.globalData.playing = true;
    //调用seek方法跳转歌曲时间
    innerAudioContext.seek(value);
    innerAudioContext.play();
  },
  
  // 随机播放时，获取当前歌曲的index在顺序列表中的索引位置，随机切换顺序列表时，改变currentIndex=找到的Index+1
  //切换播放模式
  changePlayMode: function(e){
    let type = this.data.playType;
    if (type === MusicPlayMode.normal){
      this.setData({
        playType: MusicPlayMode.loop
      })
      app.globalData.playList = app.globalData.sequenceList
      app.globalData.playMode = MusicPlayMode.loop
    }
    //模式： 循环切到随机播放
    if(type === MusicPlayMode.loop){
      this.setData({
        playType: MusicPlayMode.random
      })
      app.globalData.playList = util.shuffle(app.globalData.sequenceList)
      //当前播放的歌曲
      app.globalData.playMode = MusicPlayMode.random //模式切成随机
      var sequenceList =  app.globalData.sequenceList; //原始列表不变
      var currentIndex = app.globalData.currentIndex; //当前歌曲在原始列表的索引
      var index = app.globalData.playList.findIndex((song)=>{
       return song.id == this.data.currentSong.id
      })
      app.globalData.currentIndex = index;
    }
  //模式： 随机 切到 顺序播放
    if(type === MusicPlayMode.random){
      this.setData({
        playType: MusicPlayMode.normal
      })
      app.globalData.playList = app.globalData.sequenceList //设置播放列表为原始列表
      app.globalData.playMode = MusicPlayMode.normal  //设置播放模式为顺序播放
      var index = app.globalData.playList.findIndex((song) => {
        return song.id == this.data.currentSong.id
      })
      app.globalData.currentIndex = index;
    }
  },
  // 点击播放图标--改变播放状态
  changePlay: function(e) {
    app.globalData.playing = !app.globalData.playing;
    this.playing(app.globalData.playing)
  },
  next: function (){
    this.changeSing();
    // 列表中只有一首歌时，循环播放
    if (app.globalData.playList.length === 1) {
      this.loop()
    } else if (this.data.playType != MusicPlayMode.loop){
      app.globalData.currentIndex += 1
      if (app.globalData.currentIndex === app.globalData.playList.length) {
        app.globalData.currentIndex = 0
      }
      this.changeSongCommon();
    }
  },
  prev: function(){
    this.changeSing();
    //只有一首歌，单曲循环
    if (app.globalData.playList.length === 1) {
      this.loop()
    } else if (this.data.playType != MusicPlayMode.loop){
      app.globalData.currentIndex -= 1
      if (app.globalData.currentIndex === -1){
        app.globalData.currentIndex = app.globalData.playList.length - 1
      }
      this.changeSongCommon(); 
    }
  },
  changeSing: function(){
    innerAudioContext.stop();
    var duration = innerAudioContext.duration;
    this.setData({ audioSeek: 0, audioTime: 0, audioDuration: duration, showTime1: `00:00` });
    //当前状态暂停时，重新触发播放按钮
    if(!this.data.playing){
      this.changePlay()
    }else{
      innerAudioContext.play();
    }
  },
  changeSongCommon: function(){
    //播放列表中只有1首歌时，单曲循环
    let song = app.globalData.playList[app.globalData.currentIndex]
    let url = song.image
    this.setData({
      currentSong: song,
      imgUrl: url
    });
    this.songPlayurl();
  },
  // 循环播放
  loop: function () {
    innerAudioContext.play()
    innerAudioContext.seek(0)
    var duration = innerAudioContext.duration;
    this.setData({ audioSeek: 0, audioTime: 0, audioDuration: duration, showTime1: `00:00` });
  },
  playing: function (newPlaying) {
    // newPlaying ? this.audioPlay() : this.audioPause()
    newPlaying ? innerAudioContext.play() : innerAudioContext.pause()
    this.setData({
      playing: newPlaying
    })
  },
  songPlayurl: function(e){
    var that = this;
    var mid = that.data.currentSong.mid;
    musicTool.playMusic(mid).then(function (playRes) {
      that.setData({ audioSeek: 0, audioTime: 0, src: playRes })
      innerAudioContext.src = that.data.src;
      var duration = innerAudioContext.duration;
      var min = parseInt(duration / 60);
      var sec = parseInt(duration % 60);
      if (min.toString().length == 1) {
        min = `0${min}`;
      }
      if (sec.toString().length == 1) {
        sec = `0${sec}`;
      }
      that.setData({
        showTime2: `${min}:${sec}`
      })
      innerAudioContext.seek(0);
      innerAudioContext.play();
    })
  },
  Initialization: function () {
    var t = this;
    if (this.data.src) {
      innerAudioContext.src = this.data.src;
      innerAudioContext.play();
      innerAudioContext.pause();
      innerAudioContext.onCanplay(() => {
        innerAudioContext.duration
        setTimeout(function () {
          var duration = innerAudioContext.duration;
          var min = parseInt(duration / 60);
          var sec = parseInt(duration % 60);
          if (min.toString().length == 1) {
            min = `0${min}`;
          }
          if (sec.toString().length == 1) {
            sec = `0${sec}`;
          }
          t.setData({
            showTime2: `${min}:${sec}`
          })
        }, 1000)
      })
    }
  },
    /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var song = app.globalData.playList[app.globalData.currentIndex],
         url = song.image,
         mode = app.globalData.playMode;
    this.setData({
      currentSong: song,
      imgUrl: url,
      playType: mode
    });
    //歌曲播放自然结束时，判断模式：单曲循环-loop方法   否则-下一首方法
    innerAudioContext.onEnded((res) => {
      if (this.data.playType === MusicPlayMode.loop) {
        this.loop()
      }else{
        this.next(); 
      }
    });
    this.songPlayurl();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (e) {
    this.playing(app.globalData.playing);

    //当前状态暂停时，重新触发播放按钮
    if (!this.data.playing) {  
      this.changePlay()
    }else{
      innerAudioContext.play();
    }
    innerAudioContext.seek(0);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.Initialization();
    this.loadaudio();
  },
  loadaudio() {
    var that = this;
    //设置一个计步器
    this.data.durationIntval = setInterval(function () {
      //当歌曲在播放时执行
      if (app.globalData.playing == true) {
        //获取歌曲的播放时间，进度百分比
        var seek = that.data.audioSeek;
        var duration = innerAudioContext.duration;
        var time = that.data.audioTime;
        time = parseInt(100 * seek / duration);
        //当歌曲在播放时，每隔一秒歌曲播放时间+1，并计算分钟数与秒数
        var min = parseInt((seek + 1) / 60);
        var sec = parseInt((seek + 1) % 60);
        //填充字符串，使3:1这种呈现出 03：01 的样式
        if (min.toString().length == 1) {
          min = `0${min}`;
        }
        if (sec.toString().length == 1) {
          sec = `0${sec}`;
        }
        var min1 = parseInt(duration / 60);
        var sec1 = parseInt(duration % 60);
        if (min1.toString().length == 1) {
          min1 = `0${min1}`;
        }
        if (sec1.toString().length == 1) {
          sec1 = `0${sec1}`;
        }
        //当进度条完成，停止播放，并重设播放时间和进度条
        if (time >= 100) {
          innerAudioContext.stop();
          that.setData({ audioSeek: 0, audioTime: 0, audioDuration: duration, showTime1: `00:00` });
          return false;
        }
        //正常播放，更改进度信息，更改播放时间信息
        that.setData({ audioSeek: seek + 1, audioTime: time, audioDuration: duration, showTime1: `${min}:${sec}`, showTime2: `${min1}:${sec1}` });
      }
    }, 1000);
  },

  //生命周期函数，监听页面卸载
  onUnload: function () {
    //卸载页面，清除计步器
    clearInterval(this.data.durationIntval);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  }
})